<template>
  <ToolbarButton
    type="select"
    :model-value="currentFontSize"
    :options="fontSizeOptions"
    placeholder="字体大小"
    select-width="72px"
    @update:model-value="onFontSizeChange"
  >
    <template #option="{ option }">
      <div class="flex items-center justify-center gap-2 h-full">
        <span class="text-xs font-normal">
          {{ option.label }}
        </span>
      </div>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, computed, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { defaultDicts } from "../../../../config/constants";

defineOptions({
  name: "FontSize",
});

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<EditorProps>("editorProps");

// 字体大小选项 - 从 editorProps.dicts.fontSizes 获取，如果没有则使用默认值
const fontSizeOptions = computed(() => {
  const fontSizes = editorProps?.dicts?.fontSizes || defaultDicts.fontSizes || [];
  const locale = editorProps?.locale || "zh-CN";
  return fontSizes.map((item: any) => {
    // 处理国际化标签，根据 locale 选择对应的语言
    let label: string;
    if (typeof item.label === "string") {
      label = item.label;
    } else if (typeof item.label === "object") {
      label =
        (locale === "zh-CN" ? item.label?.zh_CN : item.label?.en_US) ||
        item.label?.zh_CN ||
        item.label?.en_US ||
        item.value;
    } else {
      label = item.value;
    }
    return {
      label,
      value: item.value,
    };
  });
});

// 计算当前字体大小
const currentFontSize = computed(() => {
  if (!editor?.value) return "default";

  const fontSize = editor.value.getAttributes("textStyle").fontSize;
  return fontSize || "default";
});

// 字体大小变化处理
const onFontSizeChange = (fontSize: string) => {
  if (fontSize && fontSize !== "default") {
    editor?.value?.chain().focus().setFontSize(fontSize).run();
  } else {
    editor?.value?.chain().focus().unsetFontSize().run();
  }
};
</script>
